# 每日定时启动客户端
import pandas as pd
import os
import pyautogui, psutil, sys
import pyscreeze, cv2
import win32api
import win32con
import webbrowser
import subprocess,time
from pathlib import Path

#   自动点击客户端菜单
def getAutoOutput(actionList):
    for actionRPA in actionList:
        if actionRPA == 'enter':
            pyautogui.press('enter')
            time.sleep(2)
        elif actionRPA[0:3] == 'tab':
            for i in range(int(actionRPA[3])):
                pyautogui.press('tab')
            time.sleep(2)
        elif actionRPA == 'shift':
            pyautogui.press('shift')
            time.sleep(2)
        else:
            pyautogui.write(actionRPA)



# 杀掉指定进程名的进程ID
def kill(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
        process.kill()


# 获取指定进程名的进程ID
def get_pid_by_name(process_name):
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == process_name:
            return proc.info['pid']
    return None


def 解锁屏幕(password):
    # 模拟按下Win键
    win32api.keybd_event(win32con.VK_LWIN, 0, 0, 0)
    time.sleep(0.5)
    win32api.keybd_event(win32con.VK_LWIN, 0, win32con.KEYEVENTF_KEYUP, 0)

    # 输入密码
    for c in password:
        win32api.keybd_event(ord(c), 0, 0, 0)
        time.sleep(0.1)
        win32api.keybd_event(ord(c), 0, win32con.KEYEVENTF_KEYUP, 0)

    # 模拟按下回车键
    win32api.keybd_event(win32con.VK_RETURN, 0, 0, 0)
    time.sleep(0.1)
    win32api.keybd_event(win32con.VK_RETURN, 0, win32con.KEYEVENTF_KEYUP, 0)

    # 等待解锁完成
    time.sleep(10)



#  图片识别点击控件
def getButton(targetImage):
    # 屏幕缩放系数 mac缩放是2 windows一般是1
    screenScale = 1
    # 事先读取按钮截图
    target = cv2.imread(targetImage, cv2.IMREAD_GRAYSCALE)
    # 先截图
    screenshot = pyscreeze.screenshot('my_screenshot.png')
    # 读取图片 灰色会快
    temp = cv2.imread(r'my_screenshot.png', cv2.IMREAD_GRAYSCALE)
    theight, twidth = target.shape[:2]
    tempheight, tempwidth = temp.shape[:2]
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp = cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale)))
    stempheight, stempwidth = scaleTemp.shape[:2]
    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
    mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if (max_val >= 0.9):
        # 计算出中心点
        top_left = max_loc
        bottom_right = (top_left[0] + twidth, top_left[1] + theight)
        tagHalfW = int(twidth / 2)
        tagHalfH = int(theight / 2)
        tagCenterX = top_left[0] + tagHalfW
        tagCenterY = top_left[1] + tagHalfH
        # 左键点击屏幕上的这个位置
        pyautogui.click(tagCenterX, tagCenterY, button='left')
    else:
        print("没找到")
        log.info(f"没找到图片{targetImage}")

是否测试=True
beginPath = os.path.split(os.path.realpath(__file__))[0]
if 是否测试==True:
    运行清单 = os.path.join(beginPath, "autoStartTest.csv")
else:
    运行清单 = os.path.join(beginPath, "autoStart.csv")
configData = pd.read_csv(运行清单)
start_time = configData["启动时间(需要同一个时间)"].iloc[0]

indexconfig = len(configData)
启动程序等待时间=5

# time.sleep(3)
def start_client():
    # 解锁屏幕(锁屏密码)
    for i in range(indexconfig):

        client = configData["系统"].iloc[i]
        clientPath = configData["客户端exe目录"].iloc[i]
        userName = configData["账号"].iloc[i]
        password = configData["密码"].iloc[i]
        processName = configData["进程名称"].iloc[i]
        窗口名称=configData["程序窗口名称"].iloc[i]
        是否启动=configData["是否启动"].iloc[i]

        if clientPath.startswith("http") and 是否启动=="Y":
            # 判断浏览器是否打开
            if webbrowser.get(using="edge").open_new("http://www.google.com") and 是否重启浏览器==False:
                # 关闭浏览器
                webbrowser.get(using="edge").close()
                # 等待一段时间
                time.sleep(5)
                # 重新打开浏览器
                webbrowser.get(using="edge").open_new(clientPath)   #新开窗口
            else:
                webbrowser.get(using="edge").open_new_tab(clientPath)   #新开标签页
            # 网页版输入账号密码
            if client == "宏汇ETF" :
                print(f"开始登录操作{client}")
                getAutoOutput(["enter", 'tab2', userName, 'tab1', password, 'enter'])
                time.sleep(启动程序等待时间*5)
            elif client == "今古ETF" :
                print(f"开始登录操作{client}")
                getAutoOutput([userName, 'tab1', password, 'enter'])
                time.sleep(启动程序等待时间*5)
            elif client == "聚安一站通" :
                print(f"开始登录操作{client}")
                getAutoOutput(['tab1',userName, 'tab1', password, 'enter'])
                time.sleep(启动程序等待时间*5)

        elif 是否启动=="Y" :
            if client == "OneQuant" :
                print(f"开始登录操作{client}")
                # hwnd = win32gui.FindWindow(None, 窗口名称)
                # win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0,0,0,0,win32con.SWP_NOMOVE|win32con.SWP_NOSIZE)
                getAutoOutput(['tab2', userName, 'tab1', password, 'enter'])
                time.sleep(启动程序等待时间)

            elif client == "手工T0" :
                print(f"开始登录操作{client}")
                getAutoOutput(['tab1', "shift", userName, 'tab1', password, 'enter'])
                time.sleep(启动程序等待时间)
            elif client == "恒生PB" :
                print(f"开始登录操作{client}")
                vbs命令 = """
                set wshell=createobject("wscript.shell")
                wshell.run "__运行路径__",1
                wscript.sleep 3500
                Dim count:count=100
                Do While wshell.AppActivate("__窗口名称__")<> true
                    wscript.sleep 200
                    count = count-1
                    If count=0 Then
                        msgbox "启动失败",,"oneQuant提示"
                        wscript.quit
                        Exit Do
                    End If
                Loop
                wscript.sleep 500
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件账号__"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件密码__"
                wshell.sendkeys "{Enter}"
                wscript.sleep 1000
                """
                script=vbs命令.replace("__窗口名称__",窗口名称).replace("__运行路径__",clientPath).replace("__软件账号__",userName).replace("__软件密码__",password)
                time.sleep(启动程序等待时间)
            elif client == "OQtest" :
                print(f"开始登录操作{client}")
                vbs命令 = """
                set wshell=createobject("wscript.shell")
                wshell.run "__运行路径__",1
                wscript.sleep 3500
                Dim count:count=100
                Do While wshell.AppActivate("__窗口名称__")<> true
                    wscript.sleep 200
                    count = count-1
                    If count=0 Then
                        msgbox "启动失败",,"oneQuant提示"
                        wscript.quit
                        Exit Do
                    End If
                Loop
                wscript.sleep 500
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件账号__"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件密码__"
                wshell.sendkeys "{Enter}"
                wscript.sleep 1000
                """
                script=vbs命令.replace("__窗口名称__",窗口名称).replace("__运行路径__",clientPath).replace("__软件账号__",userName).replace("__软件密码__",password)
                time.sleep(启动程序等待时间)
            elif client == "Ptrade" :
                print(f"开始登录操作{client}")
                vbs命令 = """
                set wshell=createobject("wscript.shell")
                wshell.run "__运行路径__",1
                wscript.sleep 3500
                Dim count:count=100
                Do While wshell.AppActivate("__窗口名称__")<> true
                    wscript.sleep 200
                    count = count-1
                    If count=0 Then
                        msgbox "启动失败",,"oneQuant提示"
                        wscript.quit
                        Exit Do
                    End If
                Loop
                wscript.sleep 500
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件账号__"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件密码__"
                wshell.sendkeys "{Enter}"
                wscript.sleep 1000
                """
                script=vbs命令.replace("__窗口名称__",窗口名称).replace("__运行路径__",clientPath).replace("__软件账号__",userName).replace("__软件密码__",password)
                time.sleep(启动程序等待时间*5)
            elif client == "络町PB" :
                print(f"开始登录操作{client}")
                vbs命令 = """
                set wshell=createobject("wscript.shell")
                wshell.run "__运行路径__",1
                wscript.sleep 3500
                Dim count:count=100
                Do While wshell.AppActivate("__窗口名称__")<> true
                    wscript.sleep 200
                    count = count-1
                    If count=0 Then
                        msgbox "启动失败",,"oneQuant提示"
                        wscript.quit
                        Exit Do
                    End If
                Loop
                wscript.sleep 500
                wshell.sendkeys "{Enter}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件账号__"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件密码__"
                wshell.sendkeys "{Enter}"
                wscript.sleep 1000
                """
                script=vbs命令.replace("__窗口名称__",窗口名称).replace("__运行路径__",clientPath).replace("__软件账号__",userName).replace("__软件密码__",password)
                time.sleep(启动程序等待时间*5)
            elif client == "迅投PB" :
                print(f"开始登录操作{client}")
                vbs命令 = """
                set wshell=createobject("wscript.shell")
                wshell.run "__运行路径__",1
                wscript.sleep 3500
                Dim count:count=100
                Do While wshell.AppActivate("__窗口名称__")<> true
                    wscript.sleep 200
                    count = count-1
                    If count=0 Then
                        msgbox "启动失败",,"oneQuant提示"
                        wscript.quit
                        Exit Do
                    End If
                Loop
                wscript.sleep 500
                wshell.sendkeys "__软件账号__"
                wshell.sendkeys "{Tab}"
                wshell.sendkeys "__软件密码__"
                wshell.sendkeys "{Enter}"
                wscript.sleep 1000
                """
                script=vbs命令.replace("__窗口名称__",窗口名称).replace("__运行路径__",clientPath).replace("__软件账号__",userName).replace("__软件密码__",password)
                time.sleep(启动程序等待时间*5)
            tmpfile = "./tmplogOnoq.vbs"
            with open(tmpfile,'w') as f:
                f.write(script)
            status=os.system(r'taskkill /F /IM {}'.format(processName))
            print(f"已踢掉程序{processName}")
            if status==0:
                print(f"已成功踢掉程序{processName}")
            else:
                print(f"踢掉程序失败{processName}")
            time.sleep(1)
            os.system("start %s" % tmpfile)
            time.sleep(2)
            os.remove(tmpfile)
start_client()
# 定时轮询启 动任务
# while True:
#     if 是否测试==False:
#         if time.localtime().tm_hour == int(str(start_time).split(":")[0]) and time.localtime().tm_hour == int(str(start_time).split(":")[2]) and 启动标识 == False:
#             是否重启浏览器=False
#             start_client()
#             time.sleep(60)
#         else:
#             # print("未到定时启动时间")
#             pass
#     elif 是否测试==True:
#         if time.localtime().tm_hour > int(str(start_time).split(":")[0]) and  启动标识 == False:
#             是否重启浏览器=False
#             start_client()
#             time.sleep(60)
#         else:
#             print("未到定时启动时间")
#             # pass





